//
//  CZComposeView.swift
//  Blog
//
//  Created by whitcast on 16/7/18.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import pop

class CZComposeView: UIView {
    // 存储目标控制器
    private var target:UIViewController?
    // 存储创建的composeButton
    private lazy var composeButtonArray = [CZComposeMenuButton]()
    // MARK: -- 懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        

        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func show(target: UIViewController) {
        self.target = target
        // 获取最上面一个window
//        let window = UIApplication.sharedApplication().windows.last!
//        window.addSubview(self)
        target.view.addSubview(self)
        // 开启动画
        for (i,value) in composeButtonArray.enumerate() {
            
            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            // 动画执行目的地
            animation.toValue = NSValue(CGPoint: CGPoint(x: value.centerX, y: value.centerY - 350))
            // 弹簧振动幅度[0,20]
            animation.springBounciness = 8
            // 抖动的初始速度
            animation.springSpeed = 10
            // 开始动画时间
            animation.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            // 执行动画
            value.pop_addAnimation(animation, forKey: nil)
            
        }
    }
    
    // 添加控件设置约束
    private func setupUI() {
        backgroundColor = UIColor.orangeColor()
        self.frame.size = CGSize(width: ScreenWidth, height: ScreenHight)
        // 添加控件
        addSubview(bgImageView)
        // 设置约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        addChildButton()
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for (i, value) in composeButtonArray.reverse().enumerate(){
            
           startAnimation(value, i: i, isUp: true)

        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_MSEC))), dispatch_get_main_queue(),{ () -> Void in
            self.removeFromSuperview()

        })
    }
    private func loadComposePlist() -> [CZComposeMenu]{
        // 获取plist文件路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        // 读取pilst文件
        let composeDicArray = NSArray(contentsOfFile: path)!
        
        var tempArray = [CZComposeMenu]()
        for dic in composeDicArray {
            let composeMenu = CZComposeMenu(dic: dic as! [String: AnyObject])
            tempArray.append(composeMenu)
        }
        return tempArray
    }
    
    private func addChildButton() {
        //  按钮的宽度
        let buttonWidth: CGFloat = 80
        //  按钮的高度
        let buttonHeight: CGFloat = 110
        //  按钮直接的间距
        let itemMargin: CGFloat = (width - 3 * buttonWidth) / 4
        //  获取plist里面的数据
        let composeMenuArray = loadComposePlist()
        
        for (i, value) in composeMenuArray.enumerate() {
            
            let button = CZComposeMenuButton()
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            button.composeMenu = value
            // 添加点击事件
            button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
            //  计算列的索引
            let colIndex = i % 3
            //  计算行的索引
            let rowIndex = i / 3
            
            //  计算x坐标
            button.x = buttonWidth * CGFloat(colIndex) + CGFloat(colIndex + 1) * itemMargin
            
            //  计算y坐标
            button.y = buttonHeight * CGFloat(rowIndex) + CGFloat(rowIndex) * itemMargin + ScreenHight
            button.setImage(UIImage(named: value.icon!), forState: .Normal)
            button.setTitle(value.title!, forState: .Normal)
            
            
            
            
            addSubview(button)
            // 添加到指定数组
            composeButtonArray.append(button)
            
        }
        
    }
    // 开启pop动画
    private func startAnimation(value: UIButton, i: Int, isUp: Bool) {
        
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        //  动画执行目的地
        let y = isUp ? value.centerY - 350 : value.centerY + 350
        
        animation.toValue = NSValue(CGPoint: CGPoint(x: value.centerX, y: y))

        //  设置弹簧效果 抖动幅度访问 range [0, 20]
        animation.springBounciness  = 8
        //  抖动的初始速度
        animation.springSpeed = 10
        //  开始动画时间
        animation.beginTime = CACurrentMediaTime() + Double(i) * 0.025
        //  执行动画
        value.pop_addAnimation(animation, forKey: nil)
    }
    
        // MARK:    - 点击按钮事件
    @objc private func buttonAction(btn: CZComposeMenuButton) {
            
            
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                
                for value in self.composeButtonArray {
                    value.alpha = 0.2
                    if value == btn {
                        //  点击放大
                        value.transform = CGAffineTransformMakeScale(3, 3)
                        
                        
                    } else {
                        //  其它按钮缩小
                        value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                    }
                    
                }
            
            
            
            
            }) { (_) -> Void in
                
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    for value in self.composeButtonArray {
                        value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                    }
                    
                    
                    
                    
                    }, completion: { (_) -> Void in
                        let classType = NSClassFromString(btn.composeMenu!.className!) as! UIViewController.Type
                        // 创建指定对象
                        let vc = classType.init()
                        // 创建导航控制器
                        let nav = UINavigationController(rootViewController: vc)
                        self.target?.presentViewController(nav, animated: true, completion: { () -> Void in
                            self.removeFromSuperview()
                        })
                        
                })
                
        }
        
   
        
        
    }
    
  

}
